package com.inspire.springboot.service.imp;

/**
 * @author :inspire
 * @date :Created in 2025/9/11 15:39
 * @description:
 * @modified By:inspire
 * @version:
 */
import com.inspire.springboot.domain.Result;
import com.inspire.springboot.domain.WeatherResponse;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.web.client.RestTemplate;

@Service
public class WeatherService {

    private static final Logger logger = LoggerFactory.getLogger(WeatherService.class);

    @Value("${tianapi.key}")
    private String apiKey;

    private final RestTemplate restTemplate = new RestTemplate();

    public Result getWeatherByCity(String city) {
        String url = "https://apis.tianapi.com/tianqi/index?key=" + apiKey + "&city=" + city + "&type=1";

        try {
            logger.info("正在请求天气数据: {}", url);
            WeatherResponse response = restTemplate.getForObject(url, WeatherResponse.class);

            if (response == null) {
                throw new RuntimeException("天气服务返回空响应");
            }

            if (response.getCode() != 200) {
                throw new RuntimeException("天气服务错误: [" + response.getCode() + "] " + response.getMsg());
            }

            if (response.getResult() == null) {
                throw new RuntimeException("天气数据为空");
            }

            logger.info("成功获取天气数据: 城市={}, 天气={}", response.getResult().getArea(), response.getResult().getWeather());
            return response.getResult();

        } catch (Exception e) {
            logger.error("获取天气信息失败: city={}", city, e);
            throw new RuntimeException("无法获取天气数据: " + e.getMessage());
        }
    }
}